package com.wxh.bomb.httpserver.server;

import com.wxh.bomb.httpserver.server.config.Mapping;
import com.wxh.bomb.httpserver.server.config.WebHandler;
import com.wxh.bomb.httpserver.server.config.Entity;

import java.util.List;
import java.util.Map;

/**
 * WebApp配置项
 * @className WebApp
 * @date 2015年12月4日 下午3:00:29
 * @author <a href="mailto:waferslove@sina.com">王星火</a>
 * @version V1.0
 */
public class WebApp {
	private static ServletContext contxt;
	static{
		// 初始化
		contxt =new ServletContext();
		// 解析Web.xml
		WebHandler web = WebHandler.parseWeb();
		
		// 加载Servlet
		List<Entity> entities = web.getEntityList();
		Map<String, String> servlet = contxt.getServlet();
		for(Entity entity : entities){
			servlet.put(entity.getName(), entity.getClz());
		}
		
		// 加载mapping
		List<Mapping> mappings = web.getMappingList();
		Map<String,String> mapping =contxt.getMapping();
		for(Mapping map : mappings){
			List<String> urls = map.getUrlPattern();
			for(String url : urls){
				mapping.put(url, map.getName());
			}
		}
	}
	
	public static Servlet getServlet(String url) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		if((null == url)||(url = url.trim()).equals("")){
			return null;
		}
		// 使用反射动态加载Servlet
		String className = contxt.getServlet().get(contxt.getMapping().get(url));
		if (null == className || "".equals(className)) {
			return null;
		}
		return (Servlet) Class.forName(className).newInstance();
	}
}
